import 'package:faker/i18n/i18n.dart';
import 'package:faker/models/local_rss.dart';
import 'package:faker/provider/local_rss_provider.dart';
import 'package:faker/res/style.dart';
import 'package:faker/utils/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as intl;

import 'base_widget.dart';
import 'loading_dialog.dart';

/// 新增或编辑TODO
class AddRssScreen extends BaseWidget {
  /// editKey: 0:新增  1:编辑  2:自定义
  /// level: 0:自动更新不提醒 1:自动更新&提醒 2:不自动更新不提醒
  final int editKey;
  final int level;
  final LocalRss rss;
  final String icon;

  AddRssScreen(
      {Key key, this.editKey = 0, this.level = 0, this.icon, this.rss});

  @override
  State<StatefulWidget> createState() {
    return _AddRssScreenSate();
  }

  @override
  BaseWidgetState<BaseWidget> attachState() {
    // TODO: implement attachState
    return null;
  }
}

class _AddRssScreenSate extends BaseWidgetState<AddRssScreen> {
  /// 是否可编辑
  bool isEnabled = true;

  String toolbarTitle = "";

  TextEditingController _titleController = TextEditingController();
  TextEditingController _descController = TextEditingController();
  TextEditingController _routeController = TextEditingController();

  final FocusNode _titleFocusNode = FocusNode();
  final FocusNode _descFocusNode = FocusNode();
  final FocusNode _routeFocusNode = FocusNode();

  /// editKey: 0:新增  1:编辑 2:已收藏 3：稍后阅读;
  int tag = 1;
  String title = '';
  String summary = '';
  String route = '';
  int priorityValue =
      0; // 优先级  0:No Update,No Remind  1:重要 Update And Remind 2:Update But Not Remind

  @override
  void initState() {
    super.initState();
    setAppBarVisible(false);
    // 判断 bean 是否有值
    if (widget.rss != null) {
      _titleController.text = widget.rss.title;
      _descController.text = widget.rss.summary;
      _routeController.text = widget.rss.route;
    }
  }

  /// 显示Loading
  _showLoading(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return new LoadingDialog(
            outsideDismiss: false,
            loadingText: S.of(context).saving,
          );
        });
  }

  /// 隐藏Loading
  _dismissLoading(BuildContext context) {
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: Container(
            padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
            child: Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(top: 58),
                  child: Text(
                    S.of(context).rsssetting,
                    style: TextStyle(
                      color: Theme.of(context).textSelectionColor,
                      fontSize: 32.0,
                      fontFamily: fontName,
                      letterSpacing: 1.0,
                    ),
                  ),
                ),
                SizedBox(
                  height: 30,
                ),
                Card(
                  margin: EdgeInsets.all(2.0),
                  elevation: 0,
                  child: ListTile(
                    title: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          S.of(context).rssName,
                          style: TextStyle(fontSize: 16),
                        ),
                        Expanded(
                          child: TextField(
                            focusNode: _titleFocusNode,
                            autofocus: false,
                            enabled: isEnabled,
                            controller: _titleController,
                            style: TextStyle(
                              fontFamily: fontName,
                              fontSize: 16,
                              color: Theme.of(context).textSelectionColor,
                            ),
                            cursorColor: Colors.blue,
                            decoration: InputDecoration.collapsed(
                              hintText: _titleController.text,
                            ),
                            maxLines: 1,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Divider(
                  color: Colors.black12,
                  height: 1.0,
                  indent: 75,
                  //endIndent: 20,
                ),
                Card(
                  margin: EdgeInsets.all(2.0),
                  elevation: 0,
                  child: ListTile(
                    title: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          S.of(context).summary,
                          style: TextStyle(fontSize: 16),
                        ),
                        Expanded(
                          child: TextField(
                            focusNode: _descFocusNode,
                            autofocus: false,
                            enabled: isEnabled,
                            controller: _descController,
                            cursorColor: Colors.blue,
                            style: TextStyle(
                              fontFamily: fontName,
                              fontSize: 16,
                              color: Theme.of(context).textSelectionColor,
                            ),
                            decoration: InputDecoration.collapsed(
                              hintText: _descController.text,
                            ),
                            maxLines: 1,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Divider(
                  color: Colors.black12,
                  height: 1.0,
                  indent: 75,
                  //endIndent: 20,
                ),
                Offstage(
                  offstage: 2 == widget.editKey || 1 == widget.editKey,
                  child: Card(
                    margin: EdgeInsets.all(2.0),
                    elevation: 0,
                    child: ListTile(
                      title: Text(
                        S.of(context).author + widget.rss.auth,
                        style: TextStyle(
                            fontSize: 16, decoration: TextDecoration.none),
                        maxLines: 3,
                        overflow: TextOverflow.fade,
                      ),
                    ),
                  ),
                ),
                Divider(
                  color: Colors.black12,
                  height: 1.0,
                  indent: 75,
                  //endIndent: 20,
                ),
                Card(
                  margin: EdgeInsets.all(2.0),
                  elevation: 0,
                  child: ListTile(
                    title: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          S.of(context).subscribeUrl,
                          style: TextStyle(fontSize: 16),
                        ),
                        Expanded(
                          child: TextField(
                            focusNode: _routeFocusNode,
                            autofocus: false,
                            enabled: isEnabled,
                            cursorColor: Colors.blue,
                            style: TextStyle(
                              fontFamily: fontName,
                              fontSize: 16,
                              color: Theme.of(context).textSelectionColor,
                            ),
                            controller: _routeController,
                            decoration: InputDecoration.collapsed(
                              hintText: _routeController.text,
                            ),
                            maxLines: 1,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Divider(
                  color: Colors.black12,
                  height: 1.0,
                  indent: 75,
                  //endIndent: 20,
                ),
                Offstage(
                  offstage: 2 == widget.editKey || 1 == widget.editKey,
                  child: Card(
                    margin: EdgeInsets.all(2.0),
                    elevation: 0,
                    child: ListTile(
                      title: Text(
                        S.of(context).example + widget.rss.example,
                        style: TextStyle(
                            fontSize: 16, decoration: TextDecoration.none),
                        maxLines: 3,
                        overflow: TextOverflow.fade,
                      ),
                    ),
                  ),
                ),
                Divider(
                  color: Colors.black12,
                  height: 1.0,
                  indent: 75,
                  //endIndent: 20,
                ),
                Offstage(
                  offstage: 2 == widget.editKey || 1 == widget.editKey,
                  child: Card(
                    margin: EdgeInsets.all(2.0),
                    elevation: 0,
                    child: ListTile(
                      title: Text(
                        S.of(context).parameter + widget.rss.parameter,
                        style: TextStyle(
                            fontSize: 16, decoration: TextDecoration.none),
                        maxLines: 3,
                        overflow: TextOverflow.fade,
                      ),
                    ),
                  ),
                ),
                Divider(
                  color: Colors.black12,
                  height: 1.0,
                  indent: 75,
                  //endIndent: 20,
                ),
                Card(
                  margin: EdgeInsets.all(2.0),
                  elevation: 0,
                  child: ListTile(
                    title: Wrap(
                      alignment: WrapAlignment.start,
                      spacing: 2, //主轴上子控件的间距
                      runSpacing: 5, //交叉轴上子控件之间的间距
                      children: <Widget>[
                        Text(
                          S.of(context).subscribeSetting,
                          style: TextStyle(fontSize: 16),
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Radio(
                              value: 1,
                              groupValue: this.priorityValue,
                              activeColor: Theme.of(context).primaryColor,
                              onChanged: (value) {
                                setState(() {
                                  this.priorityValue = value;
                                });
                              },
                            ),
                            Text(S.of(context).autoUW),
                          ],
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Radio(
                              value: 2,
                              groupValue: this.priorityValue,
                              activeColor: Theme.of(context).primaryColor,
                              onChanged: (value) {
                                setState(() {
                                  this.priorityValue = value;
                                });
                              },
                            ),
                            Text(S.of(context).autoUNW)
                          ],
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Radio(
                              value: 0,
                              groupValue: this.priorityValue,
                              activeColor: Theme.of(context).primaryColor,
                              onChanged: (value) {
                                setState(() {
                                  this.priorityValue = value;
                                });
                              },
                            ),
                            Text(S.of(context).UNW)
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
                Divider(
                  color: Colors.black12,
                  height: 1.0,
                  indent: 75,
                  //endIndent: 20,
                ),
                SizedBox(
                  height: 24,
                ),
                Card(
                  margin: EdgeInsets.all(2.0),
                  elevation: 0,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        child: RaisedButton(
                          padding: EdgeInsets.all(16.0),
                          elevation: 0.5,
                          child: Text("保存"),
                          color: Theme.of(context).primaryColorLight,
                          textColor: Colors.white,
                          onPressed: () {
                            if (widget.editKey == 0 || widget.editKey == 2) {
                              /// 新增
                              _saveRss();
                            } else if (widget.editKey == 1) {
                              /// 编辑
                              _updateRss();
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  /// 保存Rss
  Future _saveRss() async {
    title = _titleController.text;
    summary = _descController.text;
    route = _routeController.text;

    if (title.isEmpty) {
      T.show(msg: '请输入标题');
      return;
    }
    if (summary.isEmpty) {
      T.show(msg: '请输入详情');
      return;
    }
    if (route.isEmpty) {
      T.show(msg: '请输入Url');
      return;
    }
    _showLoading(context);

    insertLocalRss(new LocalRss(
        widget.rss.id,
        tag,
        "",
        title,
        summary,
        widget.rss.auth,
        route,
        widget.rss.example,
        widget.rss.parameter,
        priorityValue,
        intl.DateFormat('yyyy-MM-dd').format(DateTime.now()).toString()));
  }

  /// UpdateRss
  Future _updateRss() async {
    title = _titleController.text;
    summary = _descController.text;
    route = _routeController.text;

    if (title.isEmpty) {
      T.show(msg: '请输入标题');
      return;
    }
    if (summary.isEmpty) {
      T.show(msg: '请输入详情');
      return;
    }
    if (route.isEmpty) {
      T.show(msg: '请输入Url');
      return;
    }
    _showLoading(context);

    updateLocalRss(new LocalRss(
        widget.rss.id,
        tag,
        "",
        title,
        summary,
        widget.rss.auth,
        route,
        widget.rss.example,
        widget.rss.parameter,
        priorityValue,
        intl.DateFormat('yyyy-MM-dd').format(DateTime.now()).toString()));
  }

  insertLocalRss(LocalRss localRss) async {
    LocalRssProvider provider = new LocalRssProvider();
    var rest = provider.insert(localRss);
    rest.then((value) {
      if (value > 0) {
        _dismissLoading(context);
        T.show(msg: '保存成功');
        Navigator.of(context).pop();
      } else {
        T.show(msg: "保存失败!");
        _dismissLoading(context);
      }
    });
  }

  updateLocalRss(LocalRss localRss) async {
    LocalRssProvider provider = new LocalRssProvider();
    var rest = provider.update(localRss);
    rest.then((value) {
      if (value > 0) {
        _dismissLoading(context);
        T.show(msg: '更新成功');
        Navigator.of(context).pop();
      } else {
        T.show(msg: "更新失败!");
        _dismissLoading(context);
      }
    });
  }

  @override
  AppBar attachAppBar() {
    // TODO: implement attachAppBar
    return null;
  }

  @override
  Widget attachContentWidget(BuildContext context) {
    // TODO: implement attachContentWidget
    return null;
  }

  @override
  void onClickErrorWidget() {
    // TODO: implement onClickErrorWidget
  }
}
